// 创建 event emitter 对象
function createEmitter() {
  // eventName: []
  const listeners = {};
  return {
    // 绑定事件处理器
    on(eventName, handler, scope) {
      listeners[eventName] = (listeners[eventName] || []).concat({
        handler,
        scope,
      });
    },
    // 取消事件绑定
    off(eventName, handler) {
      listeners[eventName] = (listeners[eventName] || []).filter(
        (listener) => listener.handler !== handler
      );
    },
    // 触发事件
    emit(eventName, ...args) {
      (listeners[eventName] || []).forEach(({ handler, scope }) => {
        handler.call(scope, ...args);
      });
    },
  };
}

export default createEmitter;
